import React, { useState, useEffect } from "react";
import { Drawer, List, Card, message, Pagination } from "antd";

import { FileApi } from "@/api/file";
import { SPTDataTable } from "../SPTDataTable";
import style from "./index.module.scss";

interface IProps {
  visible: boolean;
  isCopy?: boolean;
  closeAfterClick?: boolean;
  onClose?: (ang?: any) => void;
  onChange?: (arg?: any) => void;
}

export const FileDrawer: React.FC<IProps> = ({
  visible,
  isCopy,
  closeAfterClick,
  onChange,
  onClose
}) => {
  const copy = value => {
    let textarea: any = document.createElement("textarea");
    textarea.id = "t";
    textarea.style.height = 0;
    document.body.appendChild(textarea);
    textarea.value = value;
    let selector: any = document.querySelector("#t");
    selector.select();
    document.execCommand("copy");
    document.body.removeChild(textarea);
    message.success("链接已复制到剪切板");
  };
  const [files, setFiles] = useState<IFile[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  // 获取所有文件数据
  const getFiles = async params => {
    setLoading(true);
    return FileApi.getFiles(params)
      .then(res => {
        setFiles(res[0]);
        setLoading(false);
        return res;
      })
      .catch(err => {
        setLoading(false);
      });
  };
  // 预览
  const preview = () => {
    console.log('previe')
  };
  return (
    <Drawer
      width={786}
      title="选择文件"
      closable={true}
      visible={visible}
      onClose={onClose}
    >
      <SPTDataTable
        searchFields={[
          {
            label: "文件名",
            msg: "请输入文件名",
            field: "originalname"
          },
          {
            label: "文件类型",
            field: "type",
            msg: "请输入文件类型"
          }
        ]}
        columns={[]}
        data={files}
        defaultTotal={0}
        onSearch={getFiles}
        //自定义渲染每个 List Item
        customRender={data => {
          return (
            <List
              grid={{ gutter: 16, sm: 3 }}
              dataSource={files}
              renderItem={(file: IFile) => (
                <List.Item>
                  <Card
                    hoverable
                    cover={
                      <div className={style.preview} onClick={preview}>
                        <img src={file.url} alt={file.originalname} />
                      </div>
                    }
                    onClick={() => {
                      isCopy && copy(file.url);
                      onChange && onChange(file.url);
                      closeAfterClick && onClose();
                    }}
                  >
                    <Card.Meta title={file.originalname} />
                  </Card>
                </List.Item>
              )}
            />
          );
        }}
      />
    </Drawer>
  );
};
